package com.fakesmoker.aidawnda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fakesmoker.aidawnda.model.dto.app.AppQueryRequest;
import com.fakesmoker.aidawnda.model.entity.App;
import com.fakesmoker.aidawnda.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Service
@Slf4j
public class AppCacheService implements com.fakesmoker.aidawnda.service.AppCacheService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private AppService appService;

    private static final String COMMON_CACHE_KEY = "app_recommend_common";
    private static final String USER_CACHE_KEY_PREFIX = "app_recommend_";

    public Page<App> getRecommendApps(Long userId, AppQueryRequest appQueryRequest) {
        // 先查通用缓存
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        Page<App> commonAppPage = (Page<App>) valueOperations.get(COMMON_CACHE_KEY);
        if (commonAppPage != null) {
            return commonAppPage;
        }

        // 再查个性化缓存
        String hashedUserId = String.valueOf(userId.hashCode());
        String userCacheKey = USER_CACHE_KEY_PREFIX + hashedUserId;
        Page<App> userAppPage = (Page<App>) valueOperations.get(userCacheKey);
        if (userAppPage != null) {
            return userAppPage;
        }

        // 查询数据库
        long current = appQueryRequest.getCurrent();
        long size = appQueryRequest.getPageSize();
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        Page<App> appPage = appService.page(new Page<>(current, size), queryWrapper);

        // 写缓存
        try {
            long expireTime = 50000 + new Random().nextInt(10000); // 50秒 + 随机10秒
            valueOperations.set(COMMON_CACHE_KEY, appPage, expireTime, TimeUnit.MILLISECONDS);
            valueOperations.set(userCacheKey, appPage, expireTime, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set error", e);
        }
        return appPage;
    }
}